<template>
  <div>
    <label v-show="!todo.isEdit">
      <input type="checkbox" name="listItem" :checked="todo.completed" @change="check(todo.id)">
      <span>{{ todo.title }}</span>
    </label>
    <input v-show="todo.isEdit" type="text" :value="todo.title" ref="edit" @keyup.enter="editTodo(todo, $event)">
    <button @click="handleEdit(todo)">编辑</button>
    <button @click="del(todo.id)">删除</button>
  </div>
</template>

<script>
/* eslint-disable */
import PubSub from 'pubsub-js'
export default {
  name: 'TodoList',
  // props: ['todo', 'checkTodo', 'deleteTodo'],
  props: ['todo'],
  methods: {
    check(val) {
      // this.checkTodo(val)
      this.$bus.$emit('checkTodo', val)
    },
    del(val) {
      if (confirm('确定删除吗？')) {
        // this.deleteTodo(val)
        // this.$bus.$emit('deleteTodo', val)
        PubSub.publish('deleteTodo', val)
      }
    },
    handleEdit(todo) {
      // this.$refs.edit.focus()
      if (todo.hasOwnProperty('isEdit')) {
        todo.isEdit = true
      } else {
        this.$set(todo, 'isEdit', true)
      }
      this.$nextTick(() => {
        this.$refs.edit.focus()
      })
    },
    editTodo(todo, e) {
      if (!e.target.value) return alert('编辑内容不能为空')
      this.$bus.$emit('editTodo', todo.id, e.target.value)
      todo.isEdit = false
    }
  },
  beforeDestroy() {
    this.$bus.$off('checkTodo')
    this.$bus.$off('deleteTodo')
    this.$bus.$off('editTodo')
  }
}
</script>